// pages/bindingGuild/President/binding/binding.js
import WeCropper from '../../../../we-cropper/we-cropper.js';
const util = require('../../../../utils/public_func.js');

const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 50

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: { // 选择平台后返回
    guild_id: null,
    p_id: null, // 平台id
    p_name: null, //	平台名称
    p_is_paltfrom: null, // 是否全平台
    p_table_flag: null, //标签
    guild_name: null,
    type_id: [], //主播类型id
    type_name: [], //职位类型名称
    type_flag: true,
    recuitType: [],
    recuitType_nochange: [],

    checkes: false,
    disabled: true,

    text_guild: null,
    text_anchorId: null,

    reg: false,

    // 裁剪图片
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      }
    },
    tailor_show: true,

    //图片
    pitrul_one: false,
    pitrul_two: false,
    pitrul_three: false,

    //路径
    one_url: '',
    two_url: '',
    three_url: '',

    imageOne: '',
    imageTwo: '',
    imageThree: '',


    //base64
    one_base64: '',
    two_base64: '',
    three_base64: '',

  },
  //正则判定
  validateInput: function(text) {
    var data = text;
    var pattern = /^[\d;]+$/;
    if (!pattern.test(data)) {
      wx.showToast({
        icon: "none",
        title: '只能输入数字和英文分号!',
      })
      this.setData({
        reg: false,
      })
      // console.log("只能输入数字或者英文分号!");
    } else {
      this.setData({
        reg: true,
      })
    }
  },
  go_protocol: function() {
    wx.navigateTo({
      url: '../../../protocol/protocol',
    })
  },
  go_selec: function() {
    if (this.data.p_id) {
      return false;
    } else {
      wx.redirectTo({
        url: '../../platform/platform?process_flag=anchor_bind',
      })
    }

  },
  checkboxChange: function(e) {
    console.log(e.detail.value)
    this.setData({
      checkes: e.detail.value,
    })
  },
  //点击事件
  click_anchorId: function() {
    if (this.data.p_id) {
      this.setData({
        disabled: false
      })
    } else if (this.data.guild_name) {
      this.setData({
        disabled: false
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '请先选择直播平台',
      })
    }
  },
  //输入事件
  inp_anchorId: function(e) {
    console.log(e.detail.value)
    this.validateInput(e.detail.value)
    this.setData({
      text_anchorId: e.detail.value,
    })
  },

  //主播类型
  click_type() {
    let that = this;
    console.log(that.data.p_id)
    if (!that.data.p_id) {
      wx.showToast({
        title: '请先选择平台',
        icon: 'none',
      })
    } else {
      that.setData({
        type_flag: false,
        type_id: [],
        type_name: []
      })
      this.recuitType_info();
    }
  },

  //获取职位类型
  recuitType_info() {
    let that = this;
    wx.request({
      url: app.globalData.url + 'api/recruit/platfrom/type',
      data: {
        token: app.globalData.token,
      },
      method: 'POST',
      success: function(e) {
        console.log(e.data.data.recuitType);

        //直播类型
        let recuitType_new = e.data.data.recuitType;
        let recuitType = [];
        recuitType_new.map(((item, index) => {
          recuitType.push(Object.assign(item, {
            checked: false
          }))
        }))
        that.setData({
          recuitType: recuitType,
          recuitType_nochange: recuitType,

        })
      },
    })
  },

  //重置
  click_reset() {
    this.setData({
      recuitType: this.data.recuitType_nochange,
      type_name: [],
      type_id: [],
    });
  },
  //点击主播类型
  only_recuitType(e) {
    console.log(e)
    let that = this;
    var index = e.currentTarget.dataset.recuittypeindex; //获取当前点击的下标
    var _type_name = e.currentTarget.dataset.type_name;
    var type_name = this.data.type_name;
    var _type_id = e.currentTarget.dataset.id;
    var type_id = this.data.type_id;
    var recuitType = this.data.recuitType; //选项集合

    var typeName = this.data.type_name;
    var typeId = this.data.type_id;

    if (typeof(typeId) == "string") {
      var type_id = typeId.split(",");
      console.log("11111111122222+" + type_id)
    } else {
      var type_id = typeId;
      console.log(typeof(type_id))

    }
    if (typeof(typeName) == "string") {
      var type_name = typeName.split(",");
      console.log("11111111122222+" + type_name)
    } else {
      var type_name = typeName;
      console.log(typeof(type_name))

    }

    if (type_id.length < 3) {
      //类型文字
      if (type_name == "") {
        type_name.push(_type_name);
        // console.log(1)
      } else {
        if (that.indexOf(type_name, _type_name) == "-1") {
          type_name.push(_type_name);
          // console.log(2)
        } else {
          that.remove(type_name, _type_name)
        }
      }
      //类型id
      if (type_id == "") {
        type_id.push(_type_id);
        // console.log(1)
      } else {
        if (that.indexOf(type_id, _type_id) == "-1") {
          type_id.push(_type_id);
          // console.log(2)
        } else {
          that.remove(type_id, _type_id)
        }
      }
      //选中状态
      if (recuitType[index].checked) {
        recuitType[index].checked = false; //改变当前选中的checked值 取消选择
      } else {
        recuitType[index].checked = true; //改变当前选中的checked值 确认选择
      }


      this.setData({
        recuitType: recuitType,
        type_name: type_name,
        type_id: type_id
      })
    } else {
      wx.showToast({
        title: '最多选择三个',
        icon: 'none',
        duration: 500,
      })
    }

    console.log("id+" + this.data.type_id)
    console.log("type_name+" + this.data.type_name)

  },

  //关闭弹框
  modal_hide() {
    this.setData({
      type_flag: true,
    })
  },
  //设置 原型
  indexOf(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) return i;
    }
    return -1;
  },
  //设置 原型
  remove(arr, val) {
    var index = arr.indexOf(val);
    if (index > -1) {
      arr.splice(index, 1);
    }
  },

  //立即绑定
  click_bind: function() {
    var that = this;
    console.log("platfrom_id+" + that.data.p_id);
    console.log("anchor_id+" + that.data.text_anchorId);
    console.log("anchor_type+" + that.data.type_id);


    if (this.data.reg) {
      //正则正确
      if (this.data.checkes == "check") {
        // console.log("ok")
        if (this.data.guild_name) {
          if (this.data.text_anchorId) {
            // console.log("ok two")
            wx.request({
              method: "POST",
              url: app.globalData.url + 'api/mine/anchor/add',
              data: {
                token: app.globalData.token, // token
                platfrom_id: this.data.guild_id, //	平台id 传不到
                anchor_id: this.data.text_anchorId, // 主播id
                anchor_type: this.data.type_id.join(","),
                // table_flag: this.data.table_flag, // 标签
              },
              success: function(e) {
                // console.log(e)
                if (e.data.code == "-1") {
                  wx.showToast({
                    icon: "none",
                    title: e.data.message,
                  })
                } else {
                  wx.showModal({
                    content: '小主~恭喜你绑定成功啦~',
                    showCancel: false,
                    confirmColor: "#ddba69",
                    success: function() {
                      // wx.switchTab({
                      //   url: '../../../report/report',
                      // })
                      wx.reLaunch({
                        url: '../../../recruit/index/index',
                      })
                    }
                  })
                }
              }
            })
          } else {
            wx.showToast({
              icon: "none",
              title: '请先填写完整信息',
            })
          }
        } else {
          if (this.data.text_anchorId) {
            // console.log("ok two")
            if (that.data.one_base64 != "" || that.data.two_base64 != "" || that.data.three_base64 != "") {
              wx.request({
                method: "POST",
                url: app.globalData.url + 'api/mine/anchor/add',
                data: {
                  token: app.globalData.token, // token
                  platfrom_id: this.data.p_id, //	平台id
                  anchor_id: this.data.text_anchorId, // 主播id
                  anchor_type: this.data.type_id.join(","),
                  // table_flag: this.data.p_table_flag, // 标签
                },
                success: function(e) {
                  // console.log(e)
                  if (e.data.code == "-1") {
                    wx.showToast({
                      icon: "none",
                      title: e.data.message,
                    })
                  } else {
                    wx.showModal({
                      content: '小主~恭喜你绑定成功啦~',
                      showCancel: false,
                      confirmColor: "#ddba69",
                      success: function() {
                        wx.reLaunch({
                          url: '../../../recruit/index/index',
                        })
                      }
                    })
                  }
                }
              })
            } else {
              wx.showToast({
                title: '最少选一张截图哦',
                icon: 'none',
              })
            }

          } else {
            wx.showToast({
              icon: "none",
              title: '请先填写完整信息',
            })
          }
        }

      } else {
        wx.showToast({
          icon: "none",
          title: '请先阅读并勾选服务协议与保密协议',
        })
      }
    } else {
      wx.showToast({
        icon: "none",
        title: '请确认主播id格式正确',
      })
    }


  },

  //选择 裁剪图片
  click_close: function() {
    this.setData({
      tailor_show: true,
    })
  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },
  getCropperImage() {
    wx.showLoading({
      title: '加载中~',
      icon: "none",
    })
    let that = this;
    this.wecropper.getCropperImage((src) => {
      if (src) {
        // console.log('图片+'+src)
        var image_base64 = wx.getFileSystemManager().readFileSync(src, "base64")
        if (that.data.imgOne) {
          //发送请求
          wx.request({
            url: app.globalData.url + 'api/resume/uploading',
            method: "POST",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            data: {
              token: app.globalData.token,
              place: 1,
              image: image_base64 + '',
              capture: "1",
            },
            success: function(e) {
              console.log(e)
            }
          })
          that.setData({
            one_url: src,
            one_base64: image_base64 + '',
            tailor_show: true,
          })
          wx.hideLoading();
        } else if (that.data.imgTwo) {
          //发送请求
          wx.request({
            url: app.globalData.url + 'api/resume/uploading',
            method: "POST",
            data: {
              token: app.globalData.token,
              place: 2,
              image: image_base64 + '',
              capture: "1",
            },
            success: function(e) {
              console.log(e)
            }
          })
          that.setData({
            two_url: src,
            two_base64: image_base64 + '',
            tailor_show: true,
          })
          wx.hideLoading();
        } else if (that.data.imgThree) {
          //发送请求
          wx.request({
            url: app.globalData.url + 'api/resume/uploading',
            method: "POST",
            data: {
              token: app.globalData.token,
              place: 3,
              image: image_base64 + '',
              capture: "1",
            },
            success: function(e) {
              console.log(e)
            }
          })
          that.setData({
            three_url: src,
            three_base64: image_base64 + '',
            tailor_show: true,
          })
          wx.hideLoading();
        } else {}
      } else {
        console.log('获取图片地址失败，请稍后重试')
      }

    });
  },
  uploadTap() {
    const self = this;

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值
        self.wecropper.pushOrign(src)
      }
    })
  },
  //裁剪图片 初始化
  init: function() {
    const {
      cropperOpt
    } = this.data

    new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
      })
      .on('beforeImageLoad', (ctx) => {
        console.log(`before picture loaded, i can do something`)
        console.log(`current canvas context:`, ctx)
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        console.log(`picture loaded`)
        console.log(`current canvas context:`, ctx)
        wx.hideToast()
      })
      .on('beforeDraw', (ctx, instance) => {
        console.log(`before canvas draw,i can do something`)
        console.log(`current canvas context:`, ctx)
      })
      .updateCanvas()
  },



  //选择图片
  click_imgOne: function() {
    this.init();
    let that = this;
    that.setData({
      tailor_show: false,

      imgOne: true,
      imgTwo: false,
      imgThree: false,
    })
  },
  click_imgTwo: function() {
    this.init();
    let that = this;
    this.setData({
      tailor_show: false,

      imgOne: false,
      imgTwo: true,
      imgThree: false,
    })
  },
  click_imgThree: function() {
    this.init();
    let that = this;
    this.setData({
      tailor_show: false,

      imgOne: false,
      imgTwo: false,
      imgThree: true,
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.init();
    if (options.title) {
      wx.setNavigationBarTitle({
        title: options.title //页面标题为路由参数
      })
    }

    if (options.p_id) {
      let p_id = (options.p_id).toString();
      let p_name = options.p_name;
      let p_is_paltfrom = options.p_is_paltfrom;
      let p_table_flag = options.p_table_flag;
      let guild_name = options.guild_name;
      console.log("p_id+" + p_id)
      this.setData({
        p_id: p_id, //选择平台后传回的平台id
        p_name: p_name,
        p_is_paltfrom: p_is_paltfrom,
        p_table_flag: p_table_flag,
        guild_name: guild_name,
      })
    } else if (options.guild_id) {
      this.setData({
        guild_id: options.guild_id,
        table_flag: options.table_flag,
        guild_name: options.guild_name,
      })
    }
    // console.log(this.data.p_name)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})